from django.db.models import Q
from rbac.models import ResourceMutexModel, ResourceModel


def get_mutex_resources(resource_id):
    """获取与指定资源互斥的资源ID列表"""
    mutex_resources = set()
    mutex_pairs = ResourceMutexModel.objects.filter(
        Q(res1_id=resource_id) | Q(res2_id=resource_id)
    )

    for pair in mutex_pairs:
        if pair.res1_id == resource_id:
            mutex_resources.add(pair.res2_id)
        else:
            mutex_resources.add(pair.res1_id)

    return list(mutex_resources)


def filter_mutex_resources(resource_list):
    """过滤互斥资源，返回有效的资源列表"""
    if not resource_list:
        return []

    mutex_pairs = ResourceMutexModel.objects.filter(
        Q(res1_id__in=resource_list) | Q(res2_id__in=resource_list)
    )

    mutex_ids = set()
    for pair in mutex_pairs:
        if pair.res1_id in resource_list:
            mutex_ids.add(pair.res2_id)
        if pair.res2_id in resource_list:
            mutex_ids.add(pair.res1_id)

    return [res for res in resource_list if res not in mutex_ids]